package com.boot.controller;

import com.boot.dao.DepartmentDao;
import com.boot.dao.EmployeeDao;
import com.boot.entities.Department;
import com.boot.entities.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.Collection;

/**
 * <h3>springboot04-web-crud</h3>
 * <p></p>
 *
 * @author : 你的名字
 * @date : 2020-03-01 17:45
 **/
@Controller
public class EmployeeController {
    @Autowired
    private EmployeeDao employeeDao;

    @Autowired
    private DepartmentDao departmentDao;

    @GetMapping("/emps")
    public String emps(Model model) {
        Collection<Employee> employs = employeeDao.getAll();
        model.addAttribute("emps", employs);
        //thymeleaf默认拼串
        //classpath:/templates/xxx.html
        return "emp/list";
    }

    /**
     * 跳转添加页面
     *
     * @param model
     * @return
     */
    @GetMapping("/emp")
    public String toAddPage(Model model) {
        Collection<Department> depts = departmentDao.getDepartments();
        model.addAttribute("depts", depts);
        return "emp/add";
    }

    @PostMapping("/emp")
    public String addEmp(Employee emp) {
        employeeDao.save(emp);
        //redirect:表示重定向到一个地址 /代表当前项目路径
        //forward：表示转发到一个地址
        return "redirect:/emps";
    }

    //跳转修改页面
    @GetMapping("/emp/{id}")
    public String toEditPage(@PathVariable("id") Integer id, Model model) {
        Employee employee = employeeDao.get(id);
        Collection<Department> depts = departmentDao.getDepartments();
        model.addAttribute("depts", depts);
        model.addAttribute("emp", employee);
        return "emp/add";
    }

    /**
     * 员工修改
     */
    @PutMapping("/emp")
    public String updateEmployee(Employee employee) {
        employeeDao.save(employee);
        return "redirect:/emps";
    }

    /**
     * 删除员工
     */
    @DeleteMapping("/emp/{id}")
    public String deleteEmp(@PathVariable("id") Integer id) {
        employeeDao.delete(id);
        return "redirect:/emps";
    }
}
